package vfs.common.tty;

import vfs.common.command.CommandFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Teletype displays messages and receives user input
 * <p/>
 * User: serge
 * Date: 15.11.13
 * Time: 2:03
 */
public class Tty
{
    static CommandFactory commandFactory;

    /** user@server:c:\path$ */
    private static final String INVITATION_FULL = "%s@%s:%s$ ";
    /** :$ */
    private static final String INVITATION = ":$ ";

    private static String username;
    private static String hostname;
    private static String path;
    private static BufferedReader isr = new BufferedReader(new InputStreamReader(System.in));
    private static boolean active = false;
    private static TtyThread thread;

    public static void setUsername(String username)
    {
        Tty.username = username;
    }

    public static void setHostname(String hostname)
    {
        Tty.hostname = hostname;
    }

    public static void setPath(String path)
    {
        Tty.path = path;
    }

    public static void setCommandFactory(CommandFactory commandFactory)
    {
        Tty.commandFactory = commandFactory;
    }

    /** Tty starts processing user input */
    public static void start()
    {
        thread = new TtyThread();
        thread.start();
    }

    /** Tty starts processing user input */
    public static void stop()
    {
        thread.finish();

        thread = null;
    }

    public static void println(String message)
    {
        System.out.println(message);
        printInvitation();
    }

    static void printInvitation()
    {
        boolean hasParams = hostname != null && username != null && path != null;
        String invitation = hasParams ? String.format(INVITATION_FULL, username, hostname, path) : INVITATION;
        System.out.print(invitation);
    }
}
